﻿using Kongt.IServices;
using Kongt.IServices.QueryModel;
using Kongt.Model;
using Kongt.Service;
using Kongt.ServiceProvider;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Transactions;
using System.Web;
using System.Web.Mvc;
using Webdiyer.WebControls.Mvc;

namespace Kongt.Web.Controllers
{

    /// <summary>
    /// 抄表
    /// </summary>
    public class MeterController : BaseUserController
    {
        private IMeterService meterService = ServiceFactory.Create<IMeterService>();
        private IChargeService chargeService = ServiceFactory.Create<IChargeService>();

        /// <summary>
        /// 手动抄表
        /// </summary>
        public ActionResult HandRead(MeterInfoQuery p)
        {
            var pModel = meterService.QueryMeters(p);
            PagedList<MeterInfo> model = new PagedList<MeterInfo>(pModel.Rows, p.PageIndex, p.PageSize, pModel.Count);
            return View(model);
        }

        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="meter"></param>
        /// <returns></returns>
        public ActionResult MeterEdit(MeterInfo meter)
        {
            if (ModelState.IsValid)
            {
                
                    try
                    {
                        if (meter.Id > 0)
                        {
                            meterService.Update(meter);
                            //更新抄表数据 更新账单信息(这里如果账单是未缴费状态 可以删除 )
                            chargeService.DeleteChargeByChargeName(string.Format("{0}年{1}月费用", meter.ReadMeterDate.Year, meter.ReadMeterDate.Month - 1));
                        }
                        else
                        {
                            meterService.Create(meter);

                        }
                        #region 更新了抄表数据  要更新缴费账单
                        //获得上次计费数据
                        var prevChargeInfo = chargeService.GetPrevChargeInfo(meter.CustomerId, meter.ReadMeterDate);

                        //本期用水
                        var waterMuch = meter.ThisShow - meter.LastShow;

                        //本期用水单价
                        var waterPrice = chargeService.GetLadderFeeCharge(new LadderFeeQuery()
                        {
                            CustomerId = meter.CustomerId,
                            WaterMuch = waterMuch
                        });

                        //水费合计
                        var totalWaterPrice = waterPrice * (decimal)waterMuch;

                        //本期附加费
                        var extendFeePrice = chargeService.GetExtendCharge(new ExtendChargeQuery()
                        {
                        });

                        //本期滞纳金 由于是抄表完成生成费用，滞纳金是在缴费时计算
                        var lateFeePrice = 0;

                        ///总价
                        var totalPrice = totalWaterPrice + extendFeePrice + lateFeePrice;

                        //抄表完成之后 要生成收费数据 默认状态未付费状态 
                        var charge = new ChargeInfo()
                        {
                            CustomId = meter.CustomerId,
                            ChargeName = string.Format("{0}年{1}月费用", meter.ReadMeterDate.Year, meter.ReadMeterDate.Month - 1),
                            LastTime = prevChargeInfo?.ThisTime,
                            LastMeterShow = (prevChargeInfo?.ThisMeterShow) == null ? meter.LastShow : (prevChargeInfo?.ThisMeterShow),
                            ThisTime = meter.ReadMeterDate.ToString("yyyy/MM/dd HH:mm"),
                            ThisMeterShow = meter.ThisShow,
                            //  用水量
                            WaterMuch = waterMuch,
                            WaterPrice = waterPrice,
                            TotalWaterPrice = totalWaterPrice,
                            ExtendPrice = extendFeePrice,
                            LateFee = lateFeePrice,//由于抄表时核算数据 此时滞纳金为0
                            TotalPrice = totalPrice,
                            State = (int)ChargeInfo.StateEnum.No,
                            CollectMoneyType = (int)ChargeInfo.CollectMoneyTypeEnum.WINDOWS//暂默认为窗口收费方式 
                        };
                        chargeService.Create(charge); 
                        return Json(new JStat());
                    }
                    catch (Exception ex)
                    {
                        return Json(new JStat() { Succeed = false, Msg = ex.Message });
                    }

                    #endregion
                 
            }
            else
            {
                return Json(new JStat() { Succeed = false, Msg = ModelState.Values.First().Errors[0].ErrorMessage });
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="area"></param>
        [HttpPost]
        public JsonResult MeterDel(long id)
        {
            //删除抄表数据 则要删除次月账单？？
            meterService.Delete(id);
            return Json(new JStat());
        }







        /// <summary>
        /// 换表管理
        /// </summary>
        public ActionResult ChangeMeter(ChangeMeterQuery p)
        {
            ViewBag.CustomerId = p.CustomerId;
            var pModel = meterService.QueryChangeMeters(p);
            PagedList<ChangeMeterInfo> model = new PagedList<ChangeMeterInfo>(pModel.Rows, p.PageIndex, p.PageSize, pModel.Count);
            return View(model);
        }


        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="meter"></param>
        /// <returns></returns>
        public ActionResult ChangeMeterEdit(ChangeMeterInfo cm)
        {
            cm.Operator = CurrentUser.UserId;
            if (ModelState.IsValid)
            {
                if (cm.Id > 0)
                {
                    meterService.UpdateChangeMeter(cm);
                }
                else
                {
                    meterService.CreateChangeMeter(cm);
                }
                return Json(new JStat());
            }
            else
            {
                return Json(new JStat() { Succeed = false, Msg = ModelState.Values.First().Errors[0].ErrorMessage });
            }
        }


        [HttpPost]
        public JsonResult ChangeMeterDel(long id)
        {
            meterService.DeleteChangeMeter(id);
            return Json(new JStat());
        }


        /// <summary>
        /// 已抄表查询
        /// </summary>
        public ActionResult ReadedSearch(MeterInfoQuery p)
        {
            var pModel = meterService.QueryMeters(p);
            PagedList<MeterInfo> model = new PagedList<MeterInfo>(pModel.Rows, p.PageIndex, p.PageSize, pModel.Count);
            return View(model);
        }


        /// <summary>
        /// 未抄表（未抄表的用户）查询
        /// </summary>
        public ActionResult NoReadedSearch(NoReadMeterQuery p)
        {
            var pModel = meterService.QueryNoReadMeterCustomers(p);
            PagedList<Customer> model = new PagedList<Customer>(pModel.Rows, p.PageIndex, p.PageSize, pModel.Count);
            return View(model);
        }

    }
}